package com.cy.sp06.fallback;

import com.cy.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class ItemFB implements FallbackProvider {

    //指定具体实现该降级类的服务
    //返回服务id
    @Override
    public String getRoute() {

        //item-service 针对item降级
        //* 对所有服务进行降级
        //null 同 * 对所有服务降级
        //return null;
        //return "*";
        return "item-service";
    }

    //返回的降级响应，封装在response对象中
    //根据应用需求，可以返回任意的响应数据
    // - 错误提示
    // - 缓存数据 - redis中以前的正常的结果
    // - 执行业务运算返回结果
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {

        //返回HTTP响应数据
        return new ClientHttpResponse() {
            //HTTP状态对象（状态码+文本）
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR;  //500错误
            }

            //HTTP状态码 value()
            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }

            //HTTP状态文本 getReasonPhrase()
            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();
            }

            //关闭流对象
            @Override
            public void close() {
                //ByteArrayInputStream： 是内存数组的流，不占用系统资源，不需要close()释放资源
            }

            //HTTP协议体
            @Override
            public InputStream getBody() throws IOException {

                //JsonResult --- {code:500,msg:系统服务故障,data:null}
                //JsonResult类重写了toString()方法，调用该方法直接将通过JsonUtils工具类转化为json字符串格式
                String json = JsonResult.err().code(500).msg("系统服务故障").toString();
                //返回 字节数组输入流，将json字符串转化为字节
                return new ByteArrayInputStream(json.getBytes("UTF-8"));
            }

            //HTTP协议头
            @Override
            public HttpHeaders getHeaders() {

                //创建Http请求头对象
                HttpHeaders head = new HttpHeaders();
                head.add("Content-Type","application/json;charset=UTF-8");

                return head;
            }
        };
    }
}
